<?php
/**
 * Created by PhpStorm.
 * User: small
 * Date: 2018/11/12
 * Time: 14:49
 */

namespace app\api\controller;

use app\api\controller\Common;
use think\Controller;
use think\Db;
use think\Request;

class Duihuan extends Controller
{

    private $coin_host_ip = '47.92.195.55';

    private $gas_default = 0.0005;//单位ether

    private $zongdizhi = '0x6878ef80A6263979a055C7C905881925E3b5586f';//兑换时用来接收扣除的ETH的钱包地址
    //M币兑换
    public function M_duihuan(){//这是M币兑换
        die(json_encode(['zt'=>0,'msg'=>'请稍后兑换']));
        $res = Request::instance();

        if ($res->isPost()){

            $uname = $res->param('uname');//当前用户名

            $ethnum = $res->param('ethnum');//ETH数量
            $ethnum=floatval($ethnum);  //数据过滤
            //合法性判断
            if($ethnum <=0 ){
                die(json_encode(['zt'=>0,'msg'=>'请输入正确的ETH数量!']));
            }

            $bizhong = $res->param('type');//要兑换的货币类型

            $mbinum = $res->param('mbinum');//要兑换的货币类型

            $user_info = Db::name('adeth')->where('uname',$uname)->find();

            $user_id = Db::name('user')->where('uname',$uname)->value('id');

            $address = $user_info['address'];

            $key = $user_info['key'];

            $eth_balance = json_decode(file_get_contents('http://' . $this->coin_host_ip . ':8883/?type=4&account=' .
                $address))->Balance;

            if ($ethnum+0.0005 >= floatval(round($eth_balance,5))){echo json_encode(['zt'=>0,'msg'=>'余额不足！']);die();}

            $zhuan = file_get_contents('http://' . $this->coin_host_ip . ':8884/?type=3&from=' .
                $address . '&privateKey=' . $key . '&to=' . $this->zongdizhi . '&value=' .
                $ethnum);

            if (strlen(json_decode($zhuan)->hash)<60){//兑换是失败时执行

                echo json_encode(['zt'=>0,'msg'=>'对换失败!']);die();

            }else{//兑换成功时执行

                if (Db::name('duihuan')->insert([

                    'uname' => $uname,

                    'uid' => $user_id,

                    'hash' => json_decode($zhuan)->hash,

                    'address' => $address,

                    'to' => $this->zongdizhi,

                    'zt' => 2,

                    'ethnmu' => $ethnum,

                    'mnum' => $mbinum,

                    'tjtime' => time(),

                    'type' => 'm'

                ])){

                    echo json_encode(['zt'=>1,'msg'=>'M币兑换申请成功！稍后查看M币余额']);

                }else{

                    echo json_encode(['zt'=>0,'msg'=>'M币兑换失败']);

                }

            }

        }else{

            echo json_encode(['zt'=>2,'msg'=>'error']);

        }


    }
    //OME兑换（暂时不可用）
    public function Ome_duihuan(){//这是OMEC兑换

        echo json_encode(['zt'=>0,'msg'=>'暂不开放']);
        die();

        $res = Request::instance();

        if ($res->isPost()){

            $uname = $res->param('uname');//当前用户名

            $ethnum = $res->param('ethnum');//ETH数量
            $ethnum=floatval($ethnum);  //数据过滤
            //合法性判断
            if($ethnum <=0 ){
                die(json_encode(['zt'=>0,'msg'=>'请输入正确的ETH数量!']));
            }

            $bizhong = $res->param('type');//要兑换的货币类型

            $omenum = $res->param('omenum');//要兑换的货币类型

            $user_info = Db::name('adeth')->where('uname',$uname)->find();

            $user_id = Db::name('user')->where('uname',$uname)->value('id');

            $address = $user_info['address'];

            $key = $user_info['key'];

            $eth_balance = json_decode(file_get_contents('http://' . $this->coin_host_ip . ':8883/?type=4&account=' .
                $address))->Balance;

            if ($ethnum+0.0009 >= floatval(round($eth_balance,5))){echo json_encode(['zt'=>0,'msg'=>'余额不足！']);die
            ();}

            $zhuan = file_get_contents('http://' . $this->coin_host_ip . ':8884/?type=3&from=' .
                $address . '&privateKey=' . $key . '&to=' . $this->zongdizhi . '&value=' .
                $ethnum);

            if (strlen(json_decode($zhuan)->hash)<60){//兑换是失败时执行

                echo json_encode(['zt'=>0,'msg'=>'OME对换失败!']);die();

            }else{//兑换成功时执行

                if (Db::name('duihuan')->insert([

                    'uname' => $uname,

                    'uid' => $user_id,

                    'hash' => json_decode($zhuan)->hash,

                    'address' => $address,

                    'to' => $this->zongdizhi,

                    'zt' => 2,

                    'ethnmu' => $ethnum,

                    'omenum' => $omenum,

                    'tjtime' => time(),

                    'type' => 'o'

                ])){

                    echo json_encode(['zt'=>1,'msg'=>'OME兑换申请成功！稍后查看OME余额']);

                }else{

                    echo json_encode(['zt'=>0,'msg'=>'OME兑换失败']);

                }

            }

        }else{

            echo json_encode(['zt'=>2,'msg'=>'error']);

        }

    }
    //兑换批量处理
    //(服务器端执行)
    //------------------------------------------------------------------------------------------------------
    public function Duihuan_all_query(){

        $data = Db::name('duihuan')->where('zt',2)->limit(30)->select();

        if ($data){

            foreach ($data as $value){

                $zt = json_decode(file_get_contents('http://47.92.195.55:8887/?type=1&hash='.$value['hash']))->hash->status;

                if (strlen($zt) <= 4){

                    $m_biandongqian = Db::name('user')->where('uname',$value['uname'])->value('quan');

                    Db::startTrans();

                    try{

//                        mylog('quan',$value['uname'],'duihuan','eth',$m_biandongqian,$value['mnum'],'用户'.$value['uname'].'使用'.$value['ethnmu']
//                            .'个ETH兑换'
//                            .$value['mnum'].'个M币');

                        Db::name('logquan')->insert([
                            'uname'=> $value['uname'],

                            'type' => 'duihuan',

                            'typeb' => 'eth',

                            'mqian' => $m_biandongqian,

                            'money' => $value['mnum'],

                            'mhou' => $m_biandongqian+$value['mnum'],

                            'oinfo' => '用户'.$value['uname'].'使用'.floatval($value['ethnmu']) .'个ETH兑换'
                                .floatval($value['mnum']).'个M币',

                            'note' => '兑换M币',

                            'time' => time()
                        ]);

                        Db::name('duihuan')->where('hash',$value['hash'])->update(['zt'=>1,'oktime'=>time()]);

                        if ($value['type'] == 'o'){

                            Db::name('user')->where('uname',$value['uname'])->setInc('ome',floatval($value['omenum']));

                        }elseif ($value['type'] == 'm'){

                            Db::name('user')->where('uname',$value['uname'])->setInc('quan',floatval($value['mnum']));

                        }else{

                            echo "异常<hr>\r\n";

                        }

                        Db::commit();

                        echo $value['uname'].'---'.$value['hash']."执行成功<br>\r\n";

                    } catch (\Exception $e) {

                        echo $value['uname'].'---'.$value['hash']."执行失败事务已会滚<br>\r\n";

                        Db::rollback();
                    }

                }else{

                    echo $value['hash']."订单处理失败(原因可能是还未到账)<hr>\r\n";

                }

            }

        }else{

            echo "没有要处理的兑换订单<hr>\r\n";

        }

    }
    //兑换页获取余额
    public function Get_yuer(){

        $res = Request::instance();

        $user_address = $res->param('address');

        $uname = $res->param('uname');

        if ($res->isPost()){

            //获取以太坊余额（真实）
//            $eth_balance = json_decode(file_get_contents('http://' . $this->coin_host_ip . ':8883/?type=4&account=' .
//                $user_address))->Balance;
            $eth_data = Db::name('adeth')->where('uname',$uname)->value('eth');

            if ($eth_data || $eth_data == 0){

                $eth_balance = $eth_data;

            }else{

                $eth_balance = false;

            }

            $m_data = Db::name('user')->where('uname',$uname)->value('quan');

            if ($m_data || $m_data == 0){

                $M_balance = $m_data;

            }else{

                $M_balance = false;

            }

            $o_data = Db::name('user')->where('uname',$uname)->value('ome');

            if ($o_data || $o_data == 0){

                $O_balance = $o_data;

            }else{

                $O_balance = false;

            }

        $data = [

            'eth' => $eth_balance,

            'mbi' => $M_balance,

            'ome' => $O_balance

        ];

            echo json_encode(['zt'=>1,'msg'=>'获取成功','data'=>$data]);


        }else{

            echo json_encode(['zt'=>2,'msg'=>'error']);

        }

    }
    //数据解密
    private function Jiemi($data)
    {

        $jiami_data = openssl_decrypt(base64_decode($data, false), "AES-128-CBC", Config::get('Key'), OPENSSL_RAW_DATA, Config::get('IV'));

        return $jiami_data;

    }

    //数据加密
    private function Jiami($data)
    {

        $jiemi_data = base64_encode(openssl_encrypt($data, "AES-128-CBC", Config::get('Key'), OPENSSL_RAW_DATA, Config::get('IV')));

        return $jiemi_data;

    }

}